package com.bbx.demo.heartbeat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.CharsetUtil;

import java.util.concurrent.TimeUnit;

/**
 * 心跳检测demo
 */
public class heartbeatServer {

    private int port = 8092;

    public heartbeatServer()  {

    }

    public static void main (String [] args) throws InterruptedException {
        ChannelHandler channelHandler = new HeartbeatServerHandle();
        new heartbeatServer().start(channelHandler);
    }

    public void start(ChannelHandler channelHandler) throws InterruptedException {
        NioEventLoopGroup bossEventExecutors = new NioEventLoopGroup();
        NioEventLoopGroup workerEventExecutors = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossEventExecutors, workerEventExecutors)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {

                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new StringDecoder(CharsetUtil.UTF_8))
                                    .addLast(new StringEncoder(CharsetUtil.UTF_8))
                                    .addLast(new IdleStateHandler(5,8,10, TimeUnit.SECONDS))
                                    .addLast(channelHandler);
                        }
                    });
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            channelFuture.channel().closeFuture().sync();
        } finally {
            bossEventExecutors.shutdownGracefully();
            workerEventExecutors.shutdownGracefully();
        }

    }
}
